<template>
  <div>
    <ht-header>登录</ht-header>
    <ht-logo></ht-logo>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="rules.user"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="rules.pass"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
      <p class="tips">
        没有账号？去<router-link to="/register">注册</router-link>
      </p>
    </van-form>
  </div>
</template>

<script>
// import axios from 'axios'
export default {
  data() {
    return {
      username: '',
      password: '',
      rules: {
        user: [
          { required: true, message: '请填写用户名', trigger: 'onChange' },
          {
            pattern: /^\d{5,11}$/,
            message: '用户名长度是5-11位数字',
            trigger: 'onChange',
          },
        ],
        pass: [
          { required: true, message: '请填写密码', trigger: 'onChange' },
          {
            pattern: /^\d{3,11}$/,
            message: '密码长度是5-11位数字',
            trigger: 'onChange',
          },
        ],
      },
    }
  },
  created() {
    //  console.log(this.$route)
    // const { username, password } = this.$route.params || this.$route.query
    const { username, password } = this.$route.query
    this.username = username
    this.password = password
  },
  methods: {
    async onSubmit(values) {
      const res = await this.$axios.post('/login', {
        username: this.username,
        password: this.password,
      })
      // console.log(res.data)
      const { statusCode, message, data } = res.data
      if (statusCode === 200) {
        this.$toast.success(message)
        localStorage.setItem('token', data.token)
        localStorage.setItem('userId', data.user.id)
        // 保存token---舔砖到个人中心
        console.log(this.$route)
        if (this.$route.query.back) {
          this.$router.back()
        } else {
          this.$router.push('/user')
        }
      } else {
        this.$toast.fail(message)
      }
    },
  },
}
</script>
<style lang="less">
.tips {
  padding: 15px;
  font-size: 16px;
  text-align: right;
  a {
    color: orange;
  }
}
// .ht-header {
//   background-color: pink;
//   .title {
//     color: red;
//   }
// }
.van-cell__title,
van-field__label {
  color: red;
}
</style>
